const dayjs = require("dayjs");
const ossClient = require("../oss/index");
const path = require("path");
const multiparty = require("multiparty");
const TaskScheduler = require("../component/TaskScheduler");
// 自定义请求头
const headers = {
  // 指定Object的存储类型。
  "x-oss-storage-class": "Standard",
  // 指定Object的访问权限。
  "x-oss-object-acl": "public-read",
  // 通过文件URL访问文件时，指定以附件形式下载文件，下载后的文件名称定义为example.txt。
  // "Content-Disposition": 'attachment; filename="example.txt"',
  // 设置Object的标签，可同时设置多个标签。
  "x-oss-tagging": "Tag1=1&Tag2=2",
  // 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
  "x-oss-forbid-overwrite": "true",
};
// 获取图片列表
exports.getImagesList = async (req, res, next) => {
  const { type } = req.query;
  const { id, team_id } = req.user;
  const imgData = [];
  // 根据type类型查询对应的图片列表
  if (type != undefined) {
    // 当前用户是否上传过照片
    const sql_img = `SELECT * from fa_images WHERE user_id = ? AND team_id = ? AND type = ?`;
    await global.query(sql_img, [id, team_id, type]).then((sqlRes) => {
      if (sqlRes.length > 0) {
        imgData.push(sqlRes);
      }
    });

    const sqlLikes = `SELECT * from fa_likes where user_id = ? AND status= ?`;
    let myindex;
    let isLike = [];
    await global.query(sqlLikes, [id, 1]).then((sqlResults) => {
      console.log("sqlResults: " + sqlResults);
      if (sqlResults.length > 0) {
        sqlResults.map((item, index) => {
          isLike.push(item["img_id"]);
        });
      }
    });
    // 全部图片 type传值查看不同的数据
    const sql_1 = `SELECT u.id,u.user_name,u.avatar_url,i.url,i.likes, i.id as img_id FROM fa_images i JOIN fa_users u ON  u.id = i.user_id WHERE i.type=? AND i.team_id=? order by likes desc`;
    const sql = `SELECT u.id,u.user_name,u.avatar_url,i.url,i.likes, i.id as img_id FROM fa_images i JOIN fa_users u ON  u.id = i.user_id WHERE i.type=? order by likes desc`;
    await global
      .query(type == 1 ? sql_1 : sql, type == 1 ? [type, team_id] : [type])
      .then((sqlResults) => {
        if (sqlResults.length > 0) {
          sqlResults.map((item, index) => {
            item["is_link"] =
              isLike != "undefined" && isLike.includes(item["img_id"]);
            if (item.id == id) {
              myindex = index;
            }
          });
          let item = sqlResults.splice(myindex, 1)[0];
          sqlResults.unshift(item);
          res.send({
            code: 200,
            msg: "success",
            data: { userimg: imgData, list: sqlResults },
          });
        } else {
          return res.cc("暂无数据");
        }
      });
  } else {
    const sqlLikes = `SELECT * from fa_likes where user_id = ?`;
    let myindex;
    let isLike = [];
    await global.query(sqlLikes, [id]).then((sqlResults) => {
      console.log("sqlResults: " + sqlResults);
      if (sqlResults.length > 0) {
        sqlResults.map((item, index) => {
          isLike.push(item["img_id"]);
        });
      }
    });
    // 全部图片
    const sql = `SELECT u.id,u.user_name,u.avatar_url,i.url,i.likes, i.id as img_id FROM fa_images i JOIN fa_users u ON  u.id = i.user_id order by likes desc`;
    await global.query(sql).then((sqlResults) => {
      if (sqlResults.length > 0) {
        sqlResults.map((item, index) => {
          item["is_link"] =
            isLike != "undefined" && isLike.includes(item["img_id"]);
          if (item.id == id) {
            myindex = index;
          }
        });
        let item = sqlResults.splice(myindex, 1)[0];
        sqlResults.unshift(item);
        res.send({ code: 200, msg: "success", data: sqlResults });
      } else {
        return res.cc("暂无数据");
      }
    });
  }
};
// 上传图片到oss上面
exports.uploadImage = async (req, res, next) => {
  try {
    const form = new multiparty.Form();
    const { id, team_id, type } = req.user;
    const sql =
      "SELECT COUNT(*) FROM  fa_images WHERE user_id =? and team_id=? and type=?";
    const [result] = await global.query(sql, [id, team_id, type]);
    if (result["COUNT(*)"] > 0) {
      return res.cc("已上传过图片,请勿重复上传");
    }
    // 上传图片需要保存在一个目录下面，目录必须存在
    form.parse(req, async (err, fields, files) => {
      if (err) {
        return res.cc(err.message);
      }
      if (files.image == undefined) {
        return res.cc("请传入上传图片参数image");
      }
      const originalFilename = files.image[0].originalFilename;
      const fileUrl = files.image[0].path;
      const filenameArr = originalFilename.split(".");
      const filenameArrpop = filenameArr.pop();
      const fileName = "id" + id + dayjs() + "." + filenameArrpop;
      const result = await ossClient.put(
        "dev/" + fileName + "",
        path.normalize(fileUrl),
        { headers }
      );
      const url = result.url;
      const description = fields.description;
      const type = fields.type;
      const upload_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      // 将图片URL存入数据库
      const sql =
        "INSERT INTO fa_images (url,name,description,user_id,team_id,type,upload_time) VALUES (?,?,?,?,?,?,?)";
      global
        .query(sql, [
          url,
          fileName,
          description,
          id,
          team_id,
          type,
          upload_time,
        ])
        .then((sqlRes) => {
          if (sqlRes.affectedRows !== 1) {
            return res.cc("上传失败");
          }
          res.cc("上传成功", 200);
        });
    });
  } catch (error) {
    global.logger.error({ status: 500, message: "图片上传失败" });
    return res.cc(error);
  }
};
// 点赞处理模块
exports.likes = async (req, res, next) => {
  const { id, team_id } = req.user;
  const { liked_user_id, img_id, type } = req.body;
  try {
    // 查询是否点赞过
    const selectRes = await global.query(
      "SELECT * FROM  fa_likes WHERE user_id = ? AND team_id = ? and img_id = ? AND `status` = ?",
      [id, team_id, img_id, 1]
    );
    if (selectRes.length >= 10 && type==1) {
      return res.cc("您已经点赞过此图片！");
    }  else if (selectRes.length > 0 && type == 2 ) {
      return res.cc("您已经点赞过此图片！");
    } else {
      // 查询库里是否有该用户的存在
      const userSql = `SELECT * FROM fa_users  WHERE team_id=? AND id=?`;
      const sqlResult = await global.query(userSql, [team_id, id]);
      if (sqlResult.length == 0) {
        res.cc("暂无用户信息");
      } else {
        // 查询数据库是否有该图片 0没有 >0 存在
        const sql = "SELECT COUNT(*) FROM  fa_images WHERE user_id =? and id=?";
        const result = await global.query(sql, [liked_user_id, img_id]);
        if (result[0]["COUNT(*)"] == 0) {
          return res.cc("图片不存在，请上传图片！");
        } else {
          const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
          const upload_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
          // 没点赞的情况
          const sqls = [
            "INSERT INTO fa_likes (user_id, team_id, img_id, liked_user_id, type, status, create_time) VALUES (?, ?, ?, ?, ?,?, ?)",
            "UPDATE fa_images SET likes = likes + 1 ,upload_time= ? WHERE id = ?",
          ];
          const params = [
            [id, team_id, img_id, liked_user_id, type, 1, create_time],
            [upload_time, img_id],
          ];
          global.runTransaction(sqls, params).then((upSqlResult) => {
            if (upSqlResult.affectedRows != 0) {
              return res.cc("点赞成功！", 200);
            }
          });
        }
      }
    }
  } catch (error) {
    console.error(error);
    global.logger.error({ status: 500, message: "点赞失败" });
    return res.cc("点赞失败");
  }
};
// 评论处理模块
exports.comment = async (req, res, next) => {
  const { id, team_id } = req.user;
  const { img_id, content } = req.body;
  const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  try {
    await global.query(
      "INSERT INTO fa_comment (img_id,status, user_id,team_id, content,create_time) VALUES (?,?,?,?,?,?)",
      [img_id, "1", id, team_id, content, create_time]
    );
    global.logger.info({
      status: 200,
      message: "评论成功",
    });
    res.cc("评论成功", 200);
  } catch (error) {
    console.error(error);
    global.logger.error({
      status: 500,
      message: "评论失败",
    });
    return res.cc("评论失败");
  }
};

const task = async function () {
  const cur_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // todo
  const sqls = [
    "SELECT * FROM fa_likes WHERE  `status` = ? ",
    "UPDATE fa_likes SET status = ? , updated_time = ? WHERE  status = ? ",
  ];
  const params = [[1], [0, cur_time, 1]];
  global.runTransaction(sqls, params).then((upSqlResult) => {
    console.log("upSqlResult----", upSqlResult);
    if (upSqlResult.affectedRows > 0) {
      return res.cc("修改成功！", 200);
    }
  });
  return console.log("允许定时任务每天零点12:59:59 运行更新数据..." + cur_time);
};

const task_Time = new TaskScheduler("0 0 1 * * *", task);

// 开启定时任务处理模块
exports.startTask = async (req, res, next) => {
  const cur_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  task_Time.start();
  res.send({
    code: 200,
    msg: "允许定时任务每天 0 0 1 运行更新数据..." + cur_time,
  });
};
// 关闭定时任务处理模块
exports.stopTask = async (req, res, next) => {
  const cur_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  task_Time.stop();
  res.send({
    code: 200,
    msg: "停止定时任务每天零点12:59:59 运行更新数据..." + cur_time,
  });
};
